<?php namespace App\Core\Repository\Criterias\Filters;

use App\Core\Repository\Criteria;
use App\Core\Repository\Repository;
use Input;

class InputKeywordsCriteria extends Criteria{
    
    protected $input = '';
    protected $fields = [];
    
    public function __construct($fields, $input = 'keywords', $default = '') {
        $this->input = Input::get($input, $default);
        if(is_string($fields)){
            $fieldsArr = explode(',', $fields);
            foreach($fieldsArr as $fieldsArrItem){
                $this->fields[] = [trim($fieldsArrItem), 'like'];
            }
        }elseif(is_array($fields)){
            $this->fields = $fields;
        }
        $this->setName('filter_keywords_'.$this->input);
    }

    //执行
    public function apply(Repository $repository){
        parent::apply($repository);
        //格式化字段名称
        $this->formatFields($this->model);
        if(!$this->input){
            return ;
        }
        $matches = [];
        //ID搜索
        if(preg_match('/^#([0-9]*)$/', $this->input, $matches)){
            $this->query->where($this->model->getTable().'.'.$this->model->getKeyName(), '=', $matches[1]);
            return ;
        }
        //单字段
        if(!count($this->fields) > 1){
            $this->query->where($this->fields[0][0], $this->fields[0][1], '%'.$this->input.'%');
            return ;
        }
        //多字段
        $this->query->where(function ($query){
            foreach($this->fields as $key => $field){
                if($key == 0){
                    $query->where($field[0], $field[1], '%'.$this->input.'%');
                }else{
                    $query->orWhere($field[0], $field[1], '%'.$this->input.'%');
                }
            }
        });
    }
    
    //格式化字段名称
    protected function formatFields($model){
        //格式化字段名称
        foreach($this->fields as $key => $item){
            $item[0] = $this->formatField($model, $item[0]);
            $this->fields[$key] = $item;
        }
    }
    
    //验证
    protected function validate(){
        if(!is_array($this->fields) || count($this->fields) < 0){
            return false;
        }
        foreach($this->fields as $item){
            if(!is_array($item) || count($item) != 2){
                return false;
            }
            if(!in_array($item[1], ['=', 'like'])){
                return false;
            }
        }
        return parent::validate();
    }
}